﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SeDuce.Model;

public partial class Management_upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Drawing.Image thumbnail_image = null;
        System.Drawing.Image original_image = null;
        System.Drawing.Bitmap final_image = null;
        System.Drawing.Graphics graphic = null;
        MemoryStream ms = null;

        try
        {
            // Get the data
            HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];

            // Retrieve the uploaded image
            if (jpeg_image_upload != null)
            {
                original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);

                // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
                ms = new MemoryStream();
                original_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                // Store the data in my custom Thumbnail object
                string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                Thumbnail thumb = new Thumbnail(jpeg_image_upload.FileName, jpeg_image_upload.FileName, ms.GetBuffer());

                // Put it all in the Session (initialize the session if necessary)			
                List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>;
                if (thumbnails == null)
                {
                    thumbnails = new List<Thumbnail>();
                    Session["file_info"] = thumbnails;
                }
                thumbnails.Add(thumb);

                Response.StatusCode = 200;
                Response.Write(thumbnail_id);
            }
        }
        catch(Exception ex)
        {
            // If any kind of error occurs return a 500 Internal Server error
            Response.StatusCode = 500;
            Response.Write("An error occured. " + ex.Message);
            Response.End();
        }
        finally
        {
            // Clean up
            if (final_image != null) final_image.Dispose();
            if (graphic != null) graphic.Dispose();
            if (original_image != null) original_image.Dispose();
            if (thumbnail_image != null) thumbnail_image.Dispose();
            if (ms != null) ms.Close();
            Response.End();
        }
    }
}